package com.nnggstory.logs.logsocket;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.ObjectInputStream;
import java.net.Socket;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.nnggstory.logs.websocket.WebSocketPushServer;

class LogConnectThread extends Thread {
	private Socket socket = null;
	private WebSocketPushServer ws = null;
	private ObjectInputStream ois = null;
	private Set<Socket> loggerSocketSet = null;
	private static final Logger logger = LoggerFactory.getLogger(LogConnectThread.class);
	
	public LogConnectThread(Socket socket, WebSocketPushServer ws, Set<Socket> loggerSocketSet) throws IOException {
		this.socket = socket;
		this.ws = ws;
		this.loggerSocketSet = loggerSocketSet;
		loggerSocketSet.add(socket);
		ois = new ObjectInputStream(
				new BufferedInputStream(socket.getInputStream()));
	}

	@Override
	public void run() {
		super.run();
		try {
			if (ois != null) {
				while(true) {
					LogSLogModel logModel = LogFactory.createLog(ois);
					ws.pushLog(socket, logModel);
				}
			}
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
		} finally {
			if (ois != null) {
				try {
					ois.close();
				} catch(Exception e) {
					logger.error(e.getMessage(), e);
				}
			}
			if (socket != null) {
				try {
					socket.close();
					loggerSocketSet.remove(socket);
				} catch(InterruptedIOException e) {
					Thread.currentThread().interrupt();
				} catch(IOException ex) {
					logger.error(ex.getMessage(), ex);
				}
			}
		}
	}
}